package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: dupeng
 * @CreateTime: 2024-10-25  17:02
 * @Description: redis 工具类
 */
@Component
public class RedisWorker {

    /**
     * 开始时间戳    2022-01-01
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 生成唯一id
     *
     * @param prefix 业务前缀
     * @return 唯一id
     */
    public long nextId(String prefix) {
        //1、获取时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long currentTimeStamp = nowSecond - BEGIN_TIMESTAMP;

        //获取当前时间精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        //2、获取序列号
        long increment = stringRedisTemplate.opsForValue().increment("incr:" + prefix + ":" + date);

        //return 0 + 时间戳 + 序列号（yyyyMMdd） 共64bit
        return currentTimeStamp << COUNT_BITS | increment;
    }


}
